<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/7/26
 * Time: 11:37
 */

namespace Biz\module\Classes\mgt;

use Biz\validate\activity\Coupon as vCoupon;
use Biz\model\activity\CouponConfig as mCouponConfig;
use Biz\cache\Coupon as cCoupon;
use Biz\model\activity\OutCouponConfig as mOutCouponConfig;


class Coupon extends \Biz\module\Classes\Coupon
{
    public static function create($shopId, $data)
    {
        $result = [];
        $data['shop_id'] = $shopId;

        //如果选择了全店商品，则强制includegoodsids为空
        if ($data['goods_range'] == mCouponConfig::GOODS_RANGE_ALL) {
            $data['include_goods_ids'] = '';
        }

        if (!vCoupon::validate($data, 'create')) {
            $msg = vCoupon::firstError();
            throw new \Exception($msg);
        }

        //验证结束和后续补充的数据
        $data['type'] = mCouponConfig::COUPON_TYPE_DISCOVER;
        $data['cate_scope'] = mCouponConfig::CATE_SCOPE_ALL;
        $data['assume'] = mCouponConfig::COUPON_ASSUME_SHOP;
        $data['people_scope'] = mCouponConfig::PEOPLE_SCOPE_ALL;
        $data['type_time'] = mCouponConfig::TYPE_TIME_STATIC;
        $data['status'] = mCouponConfig::STATUS_CAN_RECEIVE;


        //创建优惠券的个数
        $ruleConfig = json_decode($data['rule_config'], true);

        foreach ($ruleConfig as $rule) {

            unset($data['rule_config']);

            $insert = array_merge($data, $rule);

            $couponId = mCouponConfig::create($insert);

            if ($couponId > 0) {
                if ($data['channel'] == mCouponConfig::COUPON_CHANNEL_OUT_APP) {
                    $couponCode = self::genCouponCode($couponId);

                    mCouponConfig::update(['coupon_code'=>$couponCode],['coupon_id'=>$couponId]);
                }
            }


            $result[] = $couponId;

        }

        return $result;


    }

    public static function edit($shopId, $couponId, $data)
    {
        $data['shop_id'] = $shopId;
        $data['coupon_id'] = $couponId;

        $couponInfo = mCouponConfig::getCouponInfo($couponId);

        if (empty($couponInfo)) {
            throw new \Exception('该优惠券不存在');
        }

        if ($shopId > 0 && $couponInfo['shop_id'] != $shopId) {
            throw new \Exception('越权操作，该优惠券不存在');
        }

        if (!vCoupon::validate($data, 'update')) {
            $msg = vCoupon::firstError();
            throw new \Exception($msg);
        }

        if (!empty($data['incre_goods_ids'])) {
            $existsGoodsIds = explode(',', $couponInfo['include_goods_ids']);

            $increGoodsIds = explode(',', $data['incre_goods_ids']);


            $data['include_goods_ids'] = implode(',', array_unique(array_merge($existsGoodsIds, $increGoodsIds)));
        }

        unset($data['incre_goods_ids']);


        $result = mCouponConfig::update($data, ['coupon_id' => $couponId, 'shop_id' => $shopId]);


        return $couponId;
    }

    public static function detail($shopId, $couponId)
    {
        $couponInfo = mCouponConfig::getCouponInfo($couponId);

        if (empty($couponInfo)) {
            throw new \Exception('该优惠券不存在');
        }

        if ($shopId > 0 && $couponInfo['shop_id'] != $shopId) {
            throw new \Exception('越权操作，该优惠券不存在');
        }

        return $couponInfo;
    }

    public static function lists($shopId, $page)
    {
        $pageSize = 20;
        $result = ['list' => [], 'count' => 0];


        $where = ['shop_id' => $shopId];

        $count = mCouponConfig::count($where);

        $totalPage = ceil($count / $pageSize);

        $page = ($page <= $totalPage) ? $page : $totalPage;

        $limit = ($page - 1) * $pageSize;


        $result['count'] = $count;

        $list = mCouponConfig::select('*', array_merge($where, ['ORDER' => ['coupon_id' => 'DESC'], 'LIMIT' => [$limit, $pageSize]]));

        $result['list'] = array_map(function ($v) {

            unset($v['type']);
            unset($v['cate_scope']);
            unset($v['cate_ids']);
            unset($v['exclude_goods_ids']);
            unset($v['people_ids']);
            unset($v['people_scope']);

            $v['start_time'] = str_replace('-', '.', substr($v['start_time'], 0, 10));
            $v['stop_time'] = str_replace('-', '.', substr($v['stop_time'], 0, 10));

            $v['time_range'] = $v['start_time'] . '-' . $v['stop_time'];


            $v['amount_desc'] = sprintf('满%s减%s', $v['full_amount'], $v['detract_amount']);

            return $v;
        }, $list);

        return $result;


    }

    public static function changeStatus($shopId, $couponId, $status)
    {
        $couponInfo = mCouponConfig::getCouponInfo($couponId);

        if (empty($couponInfo)) {
            throw new \Exception('该优惠券不存在');
        }

        if ($shopId > 0 && $couponInfo['shop_id'] != $shopId) {
            throw new \Exception('越权操作，该优惠券不存在');
        }

        if ($couponInfo['status'] != mCouponConfig::STATUS_CAN_RECEIVE) {
            throw new \Exception('优惠券状态不可操作');
        }

        if ($status == mCouponConfig::STATUS_CAN_NOT_RECEIVE) {
            self::checkCouponCanDown($couponId, mOutCouponConfig::SUPPORT_ASSUME_SHOP);
        }

        self::setCouponCannotReceive($couponId);

        return mCouponConfig::STATUS_CAN_NOT_RECEIVE;

    }
}